<template>
  <div class="connection-dialog">
    <el-form size="small" :model="connectionInfo" label-width="80px" @keydown.enter="doOk" ref="form"
             :show-message="false">
      <div class="connection-form">
        <div class="base-info">
          <el-form-item label="名称">
            <el-input v-model.trim="connectionInfo.label" autocomplete="on" maxlength="127" />
          </el-form-item>
          <el-form-item label="主机" prop="host" required>
            <el-input v-model.trim="connectionInfo.host" autocomplete="on" maxlength="127" />
          </el-form-item>
          <el-form-item label="端口" prop="port" required>
            <el-input-number controls-position="right" v-model="connectionInfo.port" :max="65535" />
          </el-form-item>
<!--          <el-form-item label="数据库" prop="database" required>-->
<!--            <el-input v-model.trim="connectionInfo.database" maxlength="127" />-->
<!--          </el-form-item>-->
          <el-form-item label="用户名" prop="user" required>
            <el-input v-model.trim="connectionInfo.user" maxlength="127" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input type="password" v-model="connectionInfo.password" maxlength="127" show-password />
          </el-form-item>
        </div>
        <div class="advance-info">
          <el-form-item label="SSL">
            <el-switch v-model="connectionInfo.useSSL"></el-switch>
          </el-form-item>
          <el-form-item label="Unicode">
            <el-switch v-model="connectionInfo.unicode"></el-switch>
          </el-form-item>
          <el-form-item label="字符编码" prop="encoding" required>
            <el-input v-model.trim="connectionInfo.encoding" maxlength="127"></el-input>
          </el-form-item>
          <el-form-item label="时区" prop="timezone" required>
            <el-input v-model.trim="connectionInfo.timezone" maxlength="127"></el-input>
          </el-form-item>
          <el-form-item label="连接超时" prop="timeout" required>
            <el-input-number controls-position="right" v-model="connectionInfo.timeout" :max="300" />
            <span style="padding-left: 5px;">秒</span>
            <div class="tip">0 表示不超时</div>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="备注">
        <el-input :rows="3" type="textarea" v-model.trim="connectionInfo.remark" maxlength="255" show-word-limit />
      </el-form-item>
      <div style="text-align: right">
        <el-button @click="doTest" style="display: inline-block;" v-loading="isLoading"
                   :disabled="isLoading">测试连接
        </el-button>
        <el-button type="primary" @click="doOk" style="display: inline-block">确定</el-button>
        <el-button style="display: inline-block;" @click="doClose">取消</el-button>
      </div>
    </el-form>
    <div class="msg" :style="{ color: msgState ? '#67C23A' : '#F56C6C' }">{{ msg }}</div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import apis from '@/assets/apis'

const defaultConnectionInfo = {
  id: null,
  label: '',
  host: '',
  port: 3306,
  user: 'root',
  password: '',
  database: 'mysql',
  timeout: 10,
  remark: '',
  unicode: true,
  encoding: 'UTF-8',
  timezone: 'Asia/Shanghai',
  useSSL: false
}

export default {
  name: 'ConnectionDialog',
  props: {
    data: Object
  },
  mounted() {
    if (this.data) {
      this.connectionInfo = this.data
    }
  },
  data() {
    return {
      connectionInfo: {
        ...defaultConnectionInfo
      },
      msg: '',
      msgState: false,
      isLoading: false
    }
  },
  methods: {
    async doTest() {
      try {
        await this.$refs.form.validate()
      } catch (e) {
        return
      }

      this.isLoading = true
      this.connectionInfo.database = defaultConnectionInfo.database
      apis.dbm.connection.test(this.connectionInfo).then(() => {
        this.msg = '连接成功'
        this.msgState = true
      }).catch(e => {
        this.msg = e.message
        this.msgState = false
      }).finally(() => {
        this.isLoading = false
      })
    },
    doClose() {
      this.$emit('close')
    },
    async doOk() {
      try {
        await this.$refs.form.validate()
      } catch (e) {
        return
      }

      if (!this.connectionInfo.label) {
        this.connectionInfo.label = `${this.connectionInfo.host}:${this.connectionInfo.port}`
      }
      if (this.connectionInfo.id) {
        if (this.connections.some(c => c.id !== this.connectionInfo.id && c.label === this.connectionInfo.label)) {
          this.msg = `名称 ${this.connectionInfo.label} 已经存在，请换一个吧`
          return
        }
      } else {
        if (this.connections.some(c => c.label === this.connectionInfo.label)) {
          this.msg = `名称 ${this.connectionInfo.label} 已经存在，请换一个吧`
          return
        }
      }

      this.connectionInfo.database = defaultConnectionInfo.database
      apis.dbm.connection.set(this.connectionInfo)
        .then(() => {
          if (this.connectionInfo.id) {
            this.$store.commit('updateConnection', this.connectionInfo)
          } else {
            this.$store.commit('appendConnection', this.connectionInfo)
          }
          this.$emit('close')

          this.connectionInfo = {
            ...defaultConnectionInfo
          }
          this.msg = ''
          this.msgState = false
        }).catch(e => {
        console.error(e)
        this.msg = e.message
        this.msgState = false
      })
    }
  },
  computed: mapState({
    connections: state => state.connections
  })
}
</script>

<style lang="less" scoped>
.el-form {
  width: 540px;
}

.el-input-number :deep(.el-input__inner) {
  text-align: left;
}

.el-input-number.is-controls-right :deep(.el-input__wrapper) {
  padding-left: 7px;
}

.msg {
  margin-top: 10px;
  padding: 5px 0;
  font-size: 12px;
  white-space: break-spaces;
}

.connection-form {
  display: flex;
  margin-bottom: 10px;
}

.base-info {
  width: 300px;
}

.advance-info {
  margin-left: 10px;
  width: 240px;
  border-left: 1px solid #ececec;
}
</style>
